package com.xixiake.net;

import android.text.TextUtils;

import com.android.volley.AuthFailureError;
import com.android.volley.Cache;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;
import com.xixiake.utils.CommonUtil;
import com.xixiake.utils.DeviceUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * volley进行HTTP请求
 * Created by c-wanghengli on 2017/4/16.
 */
public class GsonRequest<T> extends Request<T> {

    private HashMap<String,String> mParams = new HashMap<>();
    private BaseInput<T> mBaseInput;
    private Response.Listener mListener;
    private Class<T> mClazz;

    public GsonRequest(BaseInput<T> input,Response.Listener<T> successListener,Response.ErrorListener errorListener) {
        super(input.method, input.url, errorListener);
        this.mListener = successListener;
        this.mBaseInput = input;
        this.mClazz = input.clazz;
        setShouldCache(false);
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        HashMap<String, String> headerMap = new HashMap<>();
        headerMap.put("Content-Type", "application/x-www-form-urlencoded");
        headerMap.put("X-Wap-Proxy-Cookie", "none");
        headerMap.put("Cookie", getCookies());
        return headerMap;
    }



    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        Map<String,Object> args = mBaseInput.getParams();
        if(args != null){
            for(String key : args.keySet()){
                mParams.put(key,String.valueOf(args.get(key)));
            }
        }
        return mParams;
    }

    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse response) {
        try {
            String data = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            if(!TextUtils.isEmpty(data)){
                JSONObject jsonObject = new JSONObject(data);
                if(jsonObject.has("errorCode")){
                    int error = jsonObject.getInt("errorCode");
                }
                Gson gson = CommonUtil.createBuilder().create();
                T responseObject;
                responseObject = gson.fromJson(data,mClazz);
                return Response.success(responseObject,cache(response,0));

            }else{
                return Response.error(new ParseError(response));
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void deliverResponse(T response) {
         if(mListener != null){
             mListener.onResponse(response);
         }
    }

    public String getCookies() {
        Map<String,String> commonParams = buildCommonParams();
        StringBuilder sb = new StringBuilder();
        for(String key : commonParams.keySet()){
            sb.append(key).append("=").append(commonParams.get(key));
            sb.append(";");
        }
        Map<String,String> cookies = mBaseInput.cookies;
        if(cookies != null){
            for(String key : cookies.keySet()){
                sb.append(key).append("=").append(cookies.get(key)).append(";");
            }
        }
        return sb.toString();
    }

    private Map<String, String> buildCommonParams() {
        Map<String,String> commonParams = new HashMap<>();
        String deviceId = "" ;
        try {
            deviceId = URLEncoder.encode(DeviceUtil.getIMEI(),"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        commonParams.put("TERMINAL","android_" + deviceId);
        commonParams.put("APP_TIME",System.currentTimeMillis() + "");
        return commonParams;
    }

    private static Cache.Entry cache(NetworkResponse response,long maxAge){

        return null;
    }


}
